//
//  EMLocationManager.m
//  EasyMoney
//
//  Created by 邓乐 on 2020/1/13.
//  Copyright © 2020 zh. All rights reserved.
//

#import "EMLocationManager.h"
#import <UIKit/UIKit.h>

@implementation EMLocationInfo

// 直接添加以下代码即可自动完成
- (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }
- (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; }
- (NSUInteger)hash { return [self yy_modelHash]; }
- (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; }
- (NSString *)description { return [self yy_modelDescription]; }

@end

@interface EMLocationManager ()

@property (nonatomic, strong) CLLocationManager *manager;

@end

@implementation EMLocationManager

+ (EMLocationManager *) sharedManager {
    static EMLocationManager *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[EMLocationManager alloc] init];
    });
    return shared;
}

- (id)init {
    self = [super init];
    if (self) {
        // 打开定位 然后得到数据
        _manager = [[CLLocationManager alloc] init];
        _manager.delegate = self;
        _manager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return self;
}

- (void)start {
    [_manager requestWhenInUseAuthorization];
    [_manager stopUpdatingLocation];
    [_manager requestLocation];
}

- (void)stop {
    [_manager stopUpdatingLocation];
}

// 每隔一段时间就会调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocationCoordinate2D l = [(CLLocation *)locations.lastObject coordinate];
    if (nil == self.locationInfo) {
        self.locationInfo = [[EMLocationInfo alloc] init];
    }
    self.locationInfo.latitude = l.latitude;
    self.locationInfo.longitude = l.longitude;
    [self.delegate locationManager:self didUpdateLocations:locations];
}

//失败代理方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self.delegate locationManager:self didFailWithError:error];
}

+ (BOOL)canGetLocation
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    return status != kCLAuthorizationStatusDenied && status != kCLAuthorizationStatusNotDetermined && status != kCLAuthorizationStatusRestricted;
}

@end
